package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.DeleteCategoryException;
import com.itheima.dao.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Gareth Cao
 * @date 2022/4/28 10:56
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据分类的id来判断是否有菜品或套餐数据与分类相关联
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        //查询dish表中category_id是否有数据与分类表的id相对应
        QueryWrapper<Dish> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("category_id", id);
        //这是统计满足条件的数据有多少个
        int count1 = dishService.count(queryWrapper1);
        if (count1 > 0) {
            //抛出自定义异常,代码不往后面走了
            throw new DeleteCategoryException("菜品表有与分类表相关联的数据,不能删除");
        }
        //查询setmeal表中category_id是否有数据与分类表的id相对应
        QueryWrapper<Setmeal> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("category_id", id);
        //查询有符合条件的数据
        int count2 = setmealService.count(queryWrapper2);
        if (count2 > 0) {
            throw new DeleteCategoryException("套餐表有与分类表相关联的数据,不能删除");
        }

        //没有与分类表相关联的数据,删除该数据
        log.info("this: {}", this);
        this.removeById(id);
    }
}
